package com.lst.tools.custom.utils;

import com.lst.tools.basics.utils.RsaKeyHelper;
import com.lst.tools.custom.exception.ParserTokenErrorException;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import java.util.Map;

/**
 * JWT工具类
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class JwtHelper {
    /**
     * 密钥加密token
     *
     * @param claims
     * @param priKey
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(Map<String, Object> claims, byte[] priKey, Integer expire) throws Exception {
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.RS256, RsaKeyHelper.getPrivateKey(priKey));
        if (expire != null) {
            jwtBuilder.setExpiration(DateTime.now().plusSeconds(expire).toDate());
        }
        return jwtBuilder.compact();
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static Map<String, Object> parserToken(String token, byte[] pubKey) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(RsaKeyHelper.getPublicKey(pubKey)).parseClaimsJws(token);
            return claimsJws.getBody();
        } catch (Exception e) {
            throw new ParserTokenErrorException("token 解析异常");
        }
    }
}
